package cn.wolfcode.p2p.controller;

import cn.wolfcode.p2p.base.domain.RealAuth;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.CustomerException;
import cn.wolfcode.p2p.base.service.IRealAuthService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.util.JsonResult;
import cn.wolfcode.p2p.util.UploadUtil;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 实名认证controller
 */
@Controller
public class RealAuthController {

    @Autowired
    private IRealAuthService realAuthService;

    @Autowired
    private IUserInfoService userInfoService;

    @Value("${uploadPath}")
    private String uploadPath;

    /**
     * 实名认证页面
     */
    @RequestMapping("realAuth")
    public String realAuth(Model model) {
        UserInfo userInfo = userInfoService.getById(UserContext.getCurrentUser().getId());
        /*
        如果有,根据realAuthId查询,
        完成实名认证--> 跳到实名认证页面
        */
        if (userInfo.hasRealAuth()) {
            model.addAttribute("realAuth", realAuthService.getById(userInfo.getRealAuthId()));
            return "borrow/realAuth_result";
        } else if (userInfo.getRealAuthId() != null) {
            //没有实名通过,但有实名申请 -->等待审核
            model.addAttribute("auditing", true);
            return "borrow/realAuth_result";
        } else {
            //否则
            return "borrow/realAuth";
        }

    }

    @RequestMapping("realAuth_save")
    @ResponseBody
    public JsonResult realAuthSave(RealAuth realAuth) {
        JsonResult jsonResult = new JsonResult();
        try {
            realAuthService.apply(realAuth);
        } catch (CustomerException e) {
            jsonResult.setMessage(e.getMessage());
            throw new CustomerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统繁忙中,请稍后再试");
        }
        return jsonResult;
    }

    @RequestMapping("uploadPhoto")
    @ResponseBody
    public String uploadPhoto(MultipartFile photo) {
        return UploadUtil.upload(photo, uploadPath);
    }
}
